#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
全面接口测试脚本
测试所有模块的所有接口
"""

import requests
import json
import sys
import io
from datetime import datetime

if sys.platform == 'win32':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

BASE_URL = "http://localhost:8080"

test_results = []

def test_api(name, method, url, data=None, expected_keys=None):
    """通用测试函数"""
    try:
        if method == "GET":
            response = requests.get(url, timeout=10)
        elif method == "POST":
            response = requests.post(url, json=data, timeout=10)
        elif method == "PUT":
            response = requests.put(url, json=data, timeout=10)
        elif method == "DELETE":
            response = requests.delete(url, timeout=10)

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                data_check = True
                if expected_keys and isinstance(result.get("data"), dict):
                    for key in expected_keys:
                        if key not in result["data"]:
                            data_check = False
                            break

                status = "✅ 通过" if data_check else "⚠️  数据不完整"
                test_results.append((name, True, status))
                print(f"{status} - {name}")
                return True
            else:
                test_results.append((name, False, f"❌ API返回失败: {result.get('errorMsg')}"))
                print(f"❌ 失败 - {name}: {result.get('errorMsg')}")
                return False
        else:
            test_results.append((name, False, f"❌ HTTP {response.status_code}"))
            print(f"❌ 失败 - {name}: HTTP {response.status_code}")
            return False
    except Exception as e:
        test_results.append((name, False, f"❌ 异常: {str(e)}"))
        print(f"❌ 异常 - {name}: {str(e)}")
        return False

def main():
    print("=" * 80)
    print(f"{'科研专家推荐系统 - 全面接口测试':^70}")
    print(f"{'测试时间: ' + datetime.now().strftime('%Y-%m-%d %H:%M:%S'):^70}")
    print("=" * 80)

    # 1. 科研专家模块
    print("\n【1. 科研专家模块】")
    test_api("1.1 获取专家列表（默认分页）", "GET", f"{BASE_URL}/api/experts")
    test_api("1.2 获取专家列表（指定分页）", "GET", f"{BASE_URL}/api/experts?pageNum=1&pageSize=5")
    test_api("1.3 获取专家列表（权重推荐）", "GET", f"{BASE_URL}/api/experts?sortBy=weight&pageSize=3")
    test_api("1.4 获取专家列表（关键词搜索）", "GET", f"{BASE_URL}/api/experts?keyword=人工智能")
    test_api("1.5 获取专家详情", "GET", f"{BASE_URL}/api/experts/KYZJ0000100001")

    # 2. 科技成果模块
    print("\n【2. 科技成果模块】")
    test_api("2.1 获取成果列表（默认分页）", "GET", f"{BASE_URL}/api/achievements")
    test_api("2.2 获取成果列表（指定分页）", "GET", f"{BASE_URL}/api/achievements?pageNum=1&pageSize=5")
    test_api("2.3 获取成果列表（权重推荐）", "GET", f"{BASE_URL}/api/achievements?sortBy=weight&pageSize=3")
    test_api("2.4 获取成果列表（关键词搜索）", "GET", f"{BASE_URL}/api/achievements?keyword=智能")
    test_api("2.5 获取成果详情", "GET", f"{BASE_URL}/api/achievements/KJCG0000100001")

    # 3. 仪器设备模块
    print("\n【3. 仪器设备模块】")
    test_api("3.1 获取设备列表（默认分页）", "GET", f"{BASE_URL}/api/instruments")
    test_api("3.2 获取设备列表（指定分页）", "GET", f"{BASE_URL}/api/instruments?pageNum=1&pageSize=5")
    test_api("3.3 获取设备列表（权重推荐）", "GET", f"{BASE_URL}/api/instruments?sortBy=weight&pageSize=3")
    test_api("3.4 获取设备列表（关键词搜索）", "GET", f"{BASE_URL}/api/instruments?keyword=显微镜")
    test_api("3.5 获取设备详情", "GET", f"{BASE_URL}/api/instruments/YQSB0000100001")

    # 4. 实验基地模块
    print("\n【4. 实验基地模块】")
    test_api("4.1 获取基地列表（默认分页）", "GET", f"{BASE_URL}/api/laboratories")
    test_api("4.2 获取基地列表（指定分页）", "GET", f"{BASE_URL}/api/laboratories?pageNum=1&pageSize=5")
    test_api("4.3 获取基地列表（权重推荐）", "GET", f"{BASE_URL}/api/laboratories?sortBy=weight&pageSize=3")
    test_api("4.4 获取基地列表（关键词搜索）", "GET", f"{BASE_URL}/api/laboratories?keyword=研究")
    test_api("4.5 获取基地详情", "GET", f"{BASE_URL}/api/laboratories/SYJD0000100001")

    # 5. 其他资源模块
    print("\n【5. 其他资源模块】")
    test_api("5.1 获取资源列表（默认分页）", "GET", f"{BASE_URL}/api/other-resources")
    test_api("5.2 获取资源列表（指定分页）", "GET", f"{BASE_URL}/api/other-resources?pageNum=1&pageSize=5")
    test_api("5.3 获取资源列表（权重推荐）", "GET", f"{BASE_URL}/api/other-resources?sortBy=weight&pageSize=3")
    test_api("5.4 获取资源列表（关键词搜索）", "GET", f"{BASE_URL}/api/other-resources?keyword=数据")
    test_api("5.5 获取资源详情", "GET", f"{BASE_URL}/api/other-resources/QTZY0000100001")

    # 6. 案例展示模块
    print("\n【6. 案例展示模块】")
    test_api("6.1 获取案例列表（默认分页）", "GET", f"{BASE_URL}/api/cases")
    test_api("6.2 获取案例列表（指定分页）", "GET", f"{BASE_URL}/api/cases?pageNum=1&pageSize=5")
    test_api("6.3 获取案例详情", "GET", f"{BASE_URL}/api/cases/CASE0000100001")

    # 7. 需求表单模块
    print("\n【7. 需求表单模块】")
    test_api("7.1 获取所有需求列表", "GET", f"{BASE_URL}/api/demands")
    test_api("7.2 获取用户需求列表", "GET", f"{BASE_URL}/api/demands/user/USER0000100001")
    test_api("7.3 获取需求详情", "GET", f"{BASE_URL}/api/demands/cad84467-d31f-4203-9e6f-4201b3dc080b")

    # 8. AI智能匹配模块
    print("\n【8. AI智能匹配模块】")
    test_api("8.1 获取推荐项基础信息", "GET", f"{BASE_URL}/api/recommendation-items/09edd625-13aa-4e20-ad27-d18f526d3fa1")
    test_api("8.2 获取推荐项列表", "GET", f"{BASE_URL}/api/recommendations/3e62b48d-f8ba-4d89-b3b2-b09b24b9a4c1/items")
    test_api("8.3 获取已生成的分析报告", "GET", f"{BASE_URL}/api/recommendation-items/09edd625-13aa-4e20-ad27-d18f526d3fa1/analysis-report")

    # 9. 用户资源库模块
    print("\n【9. 用户资源库模块】")
    test_api("9.1 获取用户收藏列表", "GET", f"{BASE_URL}/api/user-resources/USER0000100001")

    # 10. AI对话历史模块
    print("\n【10. AI对话历史模块】")
    test_api("10.1 获取用户会话列表", "GET", f"{BASE_URL}/api/chat/sessions?userId=USER0000100001")

    # 打印测试总结
    print("\n" + "=" * 80)
    print(f"{'测试总结':^70}")
    print("=" * 80)

    passed = sum(1 for _, result, _ in test_results if result)
    total = len(test_results)

    print(f"\n总计: {passed}/{total} 通过 ({passed*100//total}%)")

    # 按模块分组统计
    modules = {}
    for name, result, _ in test_results:
        module = name.split('.')[0]
        if module not in modules:
            modules[module] = {"passed": 0, "total": 0}
        modules[module]["total"] += 1
        if result:
            modules[module]["passed"] += 1

    print("\n模块统计:")
    for module, stats in modules.items():
        rate = stats["passed"] * 100 // stats["total"]
        print(f"  {module}: {stats['passed']}/{stats['total']} ({rate}%)")

    if passed == total:
        print("\n🎉 所有测试通过！系统运行正常。")
    elif passed >= total * 0.8:
        print(f"\n✅ 大部分测试通过，{total - passed}个接口需要检查。")
    else:
        print(f"\n⚠️  {total - passed}个测试失败，请检查系统状态。")

    print("\n" + "=" * 80)

    return passed, total

if __name__ == "__main__":
    passed, total = main()
    sys.exit(0 if passed == total else 1)
